const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const os = require('os');

const app = express();
const port = 3000;

// 获取本机IP地址
function getLocalIP() {
  const interfaces = os.networkInterfaces();
  for (const name of Object.keys(interfaces)) {
    for (const interface of interfaces[name]) {
      const { address, family, internal } = interface;
      if (family === 'IPv4' && !internal) {
        return address;
      }
    }
  }
  return '127.0.0.1';
}

const localIP = getLocalIP();

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 添加一个测试路由
app.get('/test', (req, res) => {
  console.log('测试路由被访问');
  res.json({ message: 'Test successful!' });
});

const nacl = require('tweetnacl');
const bs58 = require('bs58');


// const dappKeyPair = nacl.sign.keyPair();
const dappKeyPair = nacl.box.keyPair();

// 测试连接
app.get('/deeplink', (req, res) => {
  const secretKey = dappKeyPair.secretKey
  // console.log("Secret Key Length:", dappKeyPair.secretKey.length);  // 应该输出 32
  const publicKey = bs58.default.encode(dappKeyPair.publicKey)
  // 返回 公钥私钥 用data包装
  const data = {
    publicKey: publicKey,
    privateKey: secretKey,
  }
  res.json({ data: data });
});

// 调用解密接口
app.get('/decrypt', (req, res) => {
  const { data, nonce, publicKey, secretKey } = req.query;
  const decryptPayload = (data, nonce, sharedSecret) => {
    if (!sharedSecret) throw new Error("missing shared secret");
    const decryptedData = nacl.box.open.after(bs58.default.decode(data), bs58.default.decode(nonce), sharedSecret);
    if (!decryptedData) {
      throw new Error("Unable to decrypt data");
    }
    return JSON.parse(Buffer.from(decryptedData).toString("utf8"));
  };
  const secretKeyArray = JSON.parse(secretKey);
  const secretKeyBuffer = Buffer.from(Object.values(secretKeyArray));
  const sharedSecretDapp = nacl.box.before(bs58.default.decode(publicKey), secretKeyBuffer);
  // const sharedSecretDapp = nacl.box.before(bs58.default.decode(publicKey), dappKeyPair.secretKey);
  // const sharedSecretDapp = nacl.box.before(bs58.default.decode(publicKey), Buffer.from(secretKey, 'base64'));
  const decryptedData = decryptPayload(data, nonce, sharedSecretDapp);


  // console.log(decryptedData, 'decryptedData');
  const dataRes = {
    decryptedData: decryptedData,
  }
  res.json({ data: dataRes });
});

// 处理 TokenPocket 回调的路由
app.post('/tp/callback', (req, res) => {
  console.log('收到请求头:', req.headers);
  console.log('收到请求体:', req.body);

  const result = req.body;
  console.log('收到 TokenPocket 回调数据:', result);

  // 根据不同的 action 处理不同的逻辑
  switch (result.action) {
    case 'login':
      handleLogin(result);
      break;
    case 'transfer':
      handleTransfer(result);
      break;
    case 'pushTransaction':
      handleTransaction(result);
      break;
    case 'sign':
      handleSign(result);
      break;
    default:
      console.log('未知的操作类型:', result.action);
  }

  res.json({ success: true });
});

// 处理登录回调
function handleLogin(result) {
  const { actionId, account, publicKey, signature } = result;
  console.log('登录信息:', {
    actionId,
    account,
    publicKey,
    signature
  });
}

// 处理转账回调
function handleTransfer(result) {
  const { actionId, txID, status } = result;
  console.log('转账结果:', {
    actionId,
    txID,
    status
  });
}

// 处理交易回调
function handleTransaction(result) {
  const { actionId, txID, status } = result;
  console.log('交易结果:', {
    actionId,
    txID,
    status
  });
}

// 处理签名回调
function handleSign(result) {
  const { actionId, signature } = result;
  console.log('签名结果:', {
    actionId,
    signature
  });
}

// 启动服务器
app.listen(port, '0.0.0.0', () => {
  console.log(`服务器运行在以下地址：`);
  console.log(`- Local: http://localhost:${port}`);
  console.log(`- Network: http://${localIP}:${port}`);
}); 